package util

import (
	"crypto/md5"
	"encoding/hex"
	"crypto/sha1"
	"strings"
	"fmt"
	"bytes"
	"net/http"
	"io/ioutil"
	"strconv"
	"time"
)

//判断字符串是否在切片中
func StringInSlice(s string, ss []string) bool {
	for _,v := range ss {
		if s == v {
			return true
		}
	}
	return false
}

//数据简单签名加密 sha1(md5())
func SignNew(s string) string {
	//MD5加密
	m := md5.New()
	m.Write([]byte(s))
	ms := hex.EncodeToString(m.Sum(nil))

	//再次sha1加密
	sh := sha1.New()
	sh.Write([]byte(ms))

	return hex.EncodeToString(sh.Sum(nil))
}

//http请求的简单封装 返回请求http状态码和结果
func HttpRequest(method string,url string,body []byte,headers map[string]string) (int,[]byte,error)  {
	//处理method
	method = strings.ToUpper(method)
	switch method {
	case "GET","POST","PUT","DELETE":
		//啥也不做通过
	default:
		return 0,nil,fmt.Errorf("unsupported method " + method)
	}

	contentReader := bytes.NewReader(body)
	req, err := http.NewRequest(method, url, contentReader)
	if err != nil {
		return 0,nil,err
	}

	//设置请求头
	for k,v := range headers {
		req.Header.Set(k,v)
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return 0,nil,err
	}

	bys,err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	fmt.Println(string(bys),url)

	if err != nil {
		return 0,nil,err
	}
	return resp.StatusCode,bys,nil

}

//字符串 转 int64
func StringToInt64(s string) int64 {
	n,_ := strconv.ParseInt(s,10,64)
	return n
}

//int64 转 string
func Int64ToString(n int64) string {
	return fmt.Sprintf("%d",n)
}

//字符串 转 int
func StringToInt(s string) int {
	n,_ := strconv.Atoi(s)
	return n
}

//int64 转 string
func IntToString(n int) string {
	return fmt.Sprintf("%d",n)
}

//标准时间 转 时间戳
func ParseTime(s string, stype int) int64 {
	var f string
	switch stype {
	case 1:
		//YY-MM-DD HH:ii:ss
		f = "2006-01-02 15:04:05"
	case 2:
		f = "2006-01-02 15:04"
	case 3:
		f = "2006-01-02"
	default:

	}
	if f == "" {
		return 0
	}

	t,err := time.ParseInLocation(f,s,time.Local)
	if err != nil {
		return 0
	}
	return t.Unix()
}

//时间戳转标准时间格式
//1-完整的 2-到分 3-到天
func TimeFormat(t int64, sType int) string {
	curTime := time.Unix(t,0)

	switch sType {
	case 1:
		return curTime.Format("2006/01/02 15:04:05")
	case 2:
		return curTime.Format("2006/01/02 15:04")
	case 3:
		return curTime.Format("2006/01/02")
	}
	return ""
}

//毫秒级时间戳转标准格式
func MilliTimeFormat(t int64) string {
	sec := t / 1000
	nsec := (t - sec * 1000) * 1e6
	return time.Unix(sec,nsec).Format("2006-01-02 15:04:05")
}


